import request from "@/axios/request";
import { ElMessage } from "element-plus";

export default {
    name: "SelectHouse",
    data() {
        return {
            loading: true,
            search: "",
            allData: [],          // 存储所有房源数据
            displayData: [],      // 存储当前显示的房源数据
            originalData: [],     // 备份原始数据用于重置搜索
            total: 0,
            // 用户信息
            userInfo: {
                tenantId: null,
                username: "",
                phone: "",
                email: ""
            },
            // 状态映射
            statusMap: {
                rented: { text: '已租', type: 'info' },
                available: { text: '待租', type: 'success' },
                pending: { text: '审核中', type: 'warning' },
                rejected: { text: '审核未通过', type: 'danger' }
            }
        };
    },
    created() {
        this.loadMyInfo();
        this.load();
    },
    methods: {
        async load() {
            this.loading = true;
            try{
                const res = await request.get("/house/findAll");
                if (res.code === 200) {
                    // 保留原始状态码，新增 displayStatus 字段用于显示
                    this.allData = (res.data || []).map(item => ({
                        ...item,
                        displayStatus: this.statusMap[item.status]?.text || '未知状态'
                    }));
                    this.total = this.allData.length;
                }
                if (res.code === 200) {
                    this.allData = res.data || [];
                    this.originalData = [...this.allData]; // 备份原始数据
                    this.displayData = [...this.allData];  // 初始化显示数据
                    this.total = this.displayData.length;
                } else {
                    ElMessage.error(res.msg || "加载失败");
                    this.displayData = [];
                    this.total = 0;
                }
            } catch (err) {
                console.error(err);
                ElMessage.error("网络错误，请稍后再试");
                this.displayData = [];
                this.total = 0;
            } finally {
                this.loading = false;
            }
        },
        
        loadMyInfo() {
            const userInfo = JSON.parse(window.sessionStorage.getItem('userInfo'));

            if (!userInfo) {
                ElMessage.error("获取用户信息失败");
                console.log("获取用户信息失败");
                return;
            }

            // 根据实际情况获取用户信息字段
            this.userInfo = {
                tenantId: userInfo.tenantId || null,
                username: userInfo.username || "",
                phone: userInfo.phone || "",
                email: userInfo.email || ""
            };
        },
        
        SignOut() {
            sessionStorage.clear();
            ElMessage({
                message: '用户退出登录',
                type: 'success',
            });
            this.$router.replace({ path: '/Login' });
        },
        
        // 搜索房源
        async SearchHouse() {
            const keyword = this.search.trim();
            if (!keyword) {
                this.ResetSearch(); // 如果关键词为空，重置搜索
                return;
            }

            this.loading = true;
            try {
                const res1 = await request.get(`/house/title/${encodeURIComponent(keyword)}`);
                const res2 = await request.get(`/house/area/${encodeURIComponent(keyword)}`);
                let res = 200;
                let mergedData = [];

                if(res1.code === 200 && res2.code === 200)
                {
                    res=200;
                    mergedData = [...res1.data, ...res2.data];
                }else if(res1.code === 200 && res2.code !== 200){
                    res=200;
                    mergedData = [...res1.data];
                }else if(res1.code !== 200 && res2.code === 200){
                    res=200;
                    mergedData = [...res2.data];
                }

                // 统一处理API响应结构
                if (res === 200) {
                    this.displayData = mergedData || [];
                    this.total = this.displayData.length;
                } else {
                    ElMessage.error(res.msg || "搜索失败");
                    this.displayData = [];
                    this.total = 0;
                }
            } catch (err) {
                console.error(err);
                ElMessage.error("网络错误，请稍后再试");
                this.displayData = [];
                this.total = 0;
            } finally {
                this.loading = false;
            }
        },
        
        // 重置搜索
        ResetSearch() {
            this.search = "";
            this.displayData = [...this.originalData]; // 恢复原始数据
            this.total = this.displayData.length;
        },
        // 状态标签类型获取方法
        getStatusTagType(status) {
            return this.statusMap[status]?.type || '';
        },
        // 状态标签文本获取方法
        getStatusLabel(status) {
            return this.statusMap[status]?.text || '未知状态';
        }
    }
}